package com.uft.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.uft.model.dao.AuditDAO;
import com.uft.model.dao.ConfigPropertyDAO;
import com.uft.model.dao.ProfileDAO;
import com.uft.model.entity.Audit;
import com.uft.model.entity.ConfigProperty;
import com.uft.model.entity.Profile;
import com.uft.model.entity.Server;
import com.uft.service.WasService;
import com.uft.utils.JDOMUtil;
import com.uft.utils.UftUtils;
import com.uft.utils.WasConfigJAXB;

@Controller
public class WasConfigController {
	@Autowired
	 private ConfigPropertyDAO configPropertyDAO;
	@Autowired
	ProfileDAO profileDAO;
	
	@Autowired
	private WasService wasService;
	
	 @Autowired
	 private  AuditDAO auditDAO;
	 
	 private  static Logger  logger = Logger.getLogger(WasConfigController.class);
	@RequestMapping(value="/getWasConfiguration", method = RequestMethod.GET)
	public ModelAndView getDeployViewPage(HttpServletRequest request,  
            HttpServletResponse response){
		ModelAndView model = new ModelAndView("wasConfiguration");
		List<Profile> profiles= profileDAO.getAllProfiles();
		logger.debug("profiles List "+profiles.size());
		model.addObject("profiles", profiles);  
		return model;
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/addWasConfiguration", method = RequestMethod.POST)
	@ResponseBody
	public String addWasConfiguration(@RequestParam("profileId") String profileId,
			@RequestParam("serverName") String serverName
			,HttpServletRequest request){
		String result="";
		logger.debug("Creating a new Was Config :"+profileId+" ServerName: "+serverName);
		ConfigProperty configProp= new ConfigProperty();
		configProp.setProfileId(Integer.parseInt(profileId));
		configProp.setServerName(serverName);
		configProp.setCreationTime(Calendar.getInstance().getTime());
		configProp.setConfigFile(WasConfigJAXB.createInitialServerConfig(serverName));		
		logger.debug("Config Prop: "+configProp);
		configPropertyDAO.addNewConfigProperty(configProp);
		logger.debug("Config Prop:"+configProp.getId());
		if(configProp.getId() >= 0){
			result="{\"Result\":\"OK\"}";
		}else{
			result="{\"Result\":\"ERROR\",\"Message\":\"Error while saving to Database\"}";
		}
		return result;
		
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/deleteWasConfiguration", method = RequestMethod.POST)
	@ResponseBody
	public String deleteWasConfiguration(@RequestParam("id") int id,HttpServletRequest request){
		String result="";
		logger.debug("Deleting a  Was Config Id:"+id);
		try{
			configPropertyDAO.deleteConfigPropertyById(id);
			result="{\"Result\":\"OK\"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		return result;
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getAvailableConfiguration", method = RequestMethod.POST)
	@ResponseBody
	public String getAvailableConfiguration(@RequestParam("profileId") String profileId,HttpServletRequest request){
		String result="";
		
		try{
		//	List<ConfigProperty> configList= configPropertyDAO.getConfigPropertyListByProfileId(Integer.parseInt(profileId));
			List<HashMap<String,String>> configList=configPropertyDAO.getConfigPropertyIdName(Integer.parseInt(profileId));
			ObjectMapper mapper = new ObjectMapper();
			String listData=mapper.writeValueAsString(configList);
			
			result="{\"Result\":\"OK\",\"Records\":"+listData+"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
		}
		logger.debug("result "+result);
		return result;
	}
	
	

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getWasConfigFile", method = RequestMethod.GET)
	@ResponseBody
	public String getWasConfigFile(@RequestParam("id") String id,HttpServletRequest request){
		String result="";		
		logger.debug("getWasConfigFile ");
		result=configPropertyDAO.getConfigFile(id);
		//logger.debug("result "+result);
		return result;
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/addWasConfigFile/{id}",method = RequestMethod.POST)
	@ResponseBody
	public String addWasConfigFile(@PathVariable("id") String id,HttpServletRequest request){
		String result="";		
		try {
			String xmlFile=UftUtils.getBody(request);
			if(xmlFile != null){
				ConfigProperty configProp=configPropertyDAO.getConfigProperty(Integer.parseInt(id));
				configProp.setConfigFile(xmlFile);
				configPropertyDAO.updateConfigProperty(configProp);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/updateWasConfiguratioRuntime/{id}",method = RequestMethod.POST)
	@ResponseBody
	public String updateWasConfiguratioRuntime(@PathVariable("id") String id,
			@RequestParam("task") String task,@RequestParam("xpathValue") String xpathValue,HttpServletRequest request){
		String result="";		
		ConfigProperty configProp=configPropertyDAO.getConfigProperty(Integer.parseInt(id));
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(configProp.getId() >= 0){
			int profileid=configProp.getProfileId();
			Calendar startCal=Calendar.getInstance();
			String message=wasService.updatWasConfiguration(String.valueOf(profileid), task, configProp.getConfigFile(),xpathValue);
			Calendar endCal=Calendar.getInstance();
			if(message.equalsIgnoreCase("Success")){
				auditDAO.addAudit(new Audit(auth.getName(),configProp.getId(),"UpdateWasConfiguration",startCal.getTime().toString(),endCal.getTime().toString(),"Upating WAS Configuration:"+task+"| XpathValue: "+xpathValue));
				result="{\"Result\":\"OK\"}";
			}else{
				result="{\"Result\":\"ERROR\",\"Message\":\""+message+"\"}";
			}
			
		}else{
			result="{\"Result\":\"ERROR\",\"Message\":\"Error while Updating\"}";
		}
		
		return result;
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getWasConfigurationBuildView", method = RequestMethod.GET)
	public ModelAndView getWasConfigurationBuildView(@RequestParam(value="id", required=true) String id, HttpServletRequest request,  
            HttpServletResponse response){
		ModelAndView model = new ModelAndView("wasConfigurationDisplay");
	//	Server server=serverDAO.getServerById(Integer.parseInt(serverId));
		ConfigProperty configProp=configPropertyDAO.getConfigProperty(Integer.parseInt(id));
		model.addObject("configProp", configProp);	
		logger.debug("Get Was Configuration View");
		return model;
	}
	
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getWasConfigurationRuntimeView", method = RequestMethod.GET)
	public ModelAndView getWasConfigurationRuntimeView(@RequestParam(value="id", required=true) String id, HttpServletRequest request,  
            HttpServletResponse response){
		ModelAndView model = new ModelAndView("wasConfigurationRuntime");
	//	Server server=serverDAO.getServerById(Integer.parseInt(serverId));
		ConfigProperty configProp=configPropertyDAO.getConfigProperty(Integer.parseInt(id));
		model.addObject("id", configProp.getId());	
		model.addObject("configFile", configProp.getConfigFile());
		logger.debug("Get Was Configuration Runtime View");
		return model;
	}
}
